'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-client';
import { motion } from 'framer-motion';
import { 
  ArrowLeft, 
  Trophy,
  Medal,
  Crown,
  Star,
  Lock,
  TrendingUp
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

export default function SocialPage() {
  const router = useRouter();
  const { user, loading: authLoading } = useAuth();
  const [activeTab, setActiveTab] = useState<'achievements' | 'leaderboard'>('achievements');
  const [achievements, setAchievements] = useState<any>(null);
  const [leaderboard, setLeaderboard] = useState<any>(null);
  const [leaderboardType, setLeaderboardType] = useState<'total' | 'weekly' | 'monthly'>('total');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/auth/login');
      } else {
        loadData();
      }
    }
  }, [authLoading, user]);

  useEffect(() => {
    if (user && activeTab === 'leaderboard') {
      loadLeaderboard();
    }
  }, [leaderboardType, activeTab, user]);

  const loadData = async () => {
    try {
      setLoading(true);
      await Promise.all([loadAchievements(), loadLeaderboard()]);
    } finally {
      setLoading(false);
    }
  };

  const loadAchievements = async () => {
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch('/api/achievements', {
        headers: { 'Authorization': `Bearer ${token}` },
      });
      const result = await response.json();
      if (result.success && result.data) {
        setAchievements(result.data);
      }
    } catch (error) {
      console.error('加载成就错误:', error);
    }
  };

  const loadLeaderboard = async () => {
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch(`/api/leaderboard?type=${leaderboardType}&limit=50`, {
        headers: { 'Authorization': `Bearer ${token}` },
      });
      const result = await response.json();
      if (result.success && result.data) {
        setLeaderboard(result.data);
      }
    } catch (error) {
      console.error('加载排行榜错误:', error);
    }
  };

  const getRarityColor = (rarity: string) => {
    switch (rarity) {
      case 'legendary': return 'text-purple-600 bg-purple-100';
      case 'epic': return 'text-pink-600 bg-pink-100';
      case 'rare': return 'text-blue-600 bg-blue-100';
      default: return 'text-gray-600 bg-gray-100';
    }
  };

  const getRankIcon = (position: number) => {
    if (position === 1) return <Crown className="w-6 h-6 text-yellow-500" />;
    if (position === 2) return <Medal className="w-6 h-6 text-gray-400" />;
    if (position === 3) return <Medal className="w-6 h-6 text-orange-400" />;
    return <span className="text-lg font-bold text-gray-600">#{position}</span>;
  };

  if (authLoading || loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      <div className="max-w-6xl mx-auto p-4 md:p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="outline" onClick={() => router.push('/dashboard')} className="flex items-center gap-2">
              <ArrowLeft className="w-4 h-4" />
              返回
            </Button>
            <h1 className="text-3xl font-bold text-gray-900">社交中心</h1>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-2">
          <Button
            variant={activeTab === 'achievements' ? 'default' : 'outline'}
            onClick={() => setActiveTab('achievements')}
            className="flex items-center gap-2"
          >
            <Trophy className="w-4 h-4" />
            成就系统
          </Button>
          <Button
            variant={activeTab === 'leaderboard' ? 'default' : 'outline'}
            onClick={() => setActiveTab('leaderboard')}
            className="flex items-center gap-2"
          >
            <TrendingUp className="w-4 h-4" />
            排行榜
          </Button>
        </div>

        {/* Achievements Tab */}
        {activeTab === 'achievements' && achievements && (
          <div className="space-y-6">
            {/* Stats Card */}
            <Card>
              <CardHeader>
                <CardTitle>成就统计</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="text-center">
                    <p className="text-3xl font-bold text-indigo-600">{achievements.stats.total_achievements || 0}</p>
                    <p className="text-sm text-gray-600">已解锁</p>
                  </div>
                  <div className="text-center">
                    <p className="text-3xl font-bold text-purple-600">{achievements.stats.total_points || 0}</p>
                    <p className="text-sm text-gray-600">总积分</p>
                  </div>
                  <div className="text-center">
                    <p className="text-3xl font-bold text-pink-600">{achievements.stats.epic_count || 0}</p>
                    <p className="text-sm text-gray-600">史诗成就</p>
                  </div>
                  <div className="text-center">
                    <p className="text-3xl font-bold text-blue-600">{achievements.stats.rare_count || 0}</p>
                    <p className="text-sm text-gray-600">稀有成就</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Achievements Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {achievements.achievements.map((achievement: any) => (
                <motion.div
                  key={achievement.id}
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className={`relative ${achievement.unlocked ? '' : 'opacity-50'}`}
                >
                  <Card className={achievement.unlocked ? 'border-2 border-indigo-300' : ''}>
                    <CardContent className="pt-6">
                      <div className="flex items-start gap-3">
                        <div className="text-4xl">{achievement.icon}</div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h3 className="font-bold">{achievement.name}</h3>
                            {!achievement.unlocked && <Lock className="w-4 h-4 text-gray-400" />}
                          </div>
                          <p className="text-sm text-gray-600 mb-2">{achievement.description}</p>
                          <div className="flex items-center gap-2">
                            <span className={`text-xs px-2 py-1 rounded ${getRarityColor(achievement.rarity)}`}>
                              {achievement.rarity}
                            </span>
                            <span className="text-xs text-gray-600">{achievement.points}积分</span>
                          </div>
                          {achievement.unlocked && achievement.unlockedAt && (
                            <p className="text-xs text-gray-500 mt-2">
                              解锁于 {new Date(achievement.unlockedAt).toLocaleDateString()}
                            </p>
                          )}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </div>
        )}

        {/* Leaderboard Tab */}
        {activeTab === 'leaderboard' && leaderboard && (
          <div className="space-y-6">
            {/* Leaderboard Type Selector */}
            <div className="flex gap-2">
              <Button
                variant={leaderboardType === 'total' ? 'default' : 'outline'}
                onClick={() => setLeaderboardType('total')}
              >
                总榜
              </Button>
              <Button
                variant={leaderboardType === 'weekly' ? 'default' : 'outline'}
                onClick={() => setLeaderboardType('weekly')}
              >
                周榜
              </Button>
              <Button
                variant={leaderboardType === 'monthly' ? 'default' : 'outline'}
                onClick={() => setLeaderboardType('monthly')}
              >
                月榜
              </Button>
            </div>

            {/* User Rank Card */}
            {leaderboard.userRank && (
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-gray-600">你的排名</p>
                      <p className="text-3xl font-bold text-indigo-600">
                        #{leaderboard.userRank.rank_position || '-'}
                      </p>
                    </div>
                    <div className="text-right">
                      <p className="text-sm text-gray-600">正确题数</p>
                      <p className="text-2xl font-bold">{leaderboard.userRank.score || 0}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Leaderboard List */}
            <Card>
              <CardHeader>
                <CardTitle>排行榜</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {leaderboard.leaderboard.map((user: any, index: number) => (
                    <div
                      key={user.id}
                      className={`flex items-center gap-4 p-3 rounded-lg ${
                        user.id === (window as any).currentUserId ? 'bg-indigo-50 border-2 border-indigo-300' : 'bg-gray-50'
                      }`}
                    >
                      <div className="w-12 flex justify-center">
                        {getRankIcon(user.rank_position || index + 1)}
                      </div>
                      <div className="flex-1">
                        <p className="font-medium">{user.display_name || user.username}</p>
                        <p className="text-sm text-gray-600">@{user.username}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-lg font-bold">
                          {user.total_correct || user.weekly_correct || user.monthly_correct || 0}
                        </p>
                        <p className="text-sm text-gray-600">正确题数</p>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        )}
      </div>
    </div>
  );
}
